package org.budo.druid.util;

import com.alibaba.druid.filter.config.ConfigTools;
import com.alibaba.druid.proxy.jdbc.DataSourceProxy;
import com.alibaba.druid.util.JdbcUtils;

/**
 * @author lmw
 */
public class DruidUtil {
    public static String getDbType(DataSourceProxy dataSource) {
        String dbType = dataSource.getDbType();

        if (null != dbType && !dbType.isEmpty() && !"null".equalsIgnoreCase(dbType)) {
            return dbType;
        }

        dbType = JdbcUtils.getDbType(dataSource.getRawJdbcUrl(), null);
        if (null != dbType && !dbType.isEmpty() && !"null".equalsIgnoreCase(dbType)) {
            return dbType;
        }

        dbType = JdbcUtils.getDbType(dataSource.getUrl(), null);
        return dbType;
    }

    public static String toString(DataSourceProxy dataSource) {
        if (null == dataSource) {
            return null;
        }

        return dataSource + ", url=" + dataSource.getUrl() + ", rawJdbcUrl=" + dataSource.getRawJdbcUrl();
    }

    public static String rsaDecrypt(String cipherText) {
        if (null == cipherText || cipherText.trim().isEmpty() //
                || cipherText.length() != 88 && !cipherText.endsWith("==")) {
            return cipherText;
        }

        try {
            return ConfigTools.decrypt(cipherText);
        } catch (Exception e) {
            throw new RuntimeException("#39 cipherText=" + cipherText + ", e=" + e, e);
        }
    }

    public static String rsaEncrypt(String plainText) {
        if (null == plainText || plainText.trim().isEmpty()) {
            return plainText;
        }

        try {
            return ConfigTools.encrypt(plainText);
        } catch (Exception e) {
            throw new RuntimeException("#56 plainText=" + plainText + ", e=" + e, e);
        }
    }
}